class GalleriesController < ApplicationController 
	before_filter :find_model_instance, :only => [:show, :edit, :update, :destroy]

	after_filter :update_user_groups, :only => [:create, :update]

  # GET /galleries
  # GET /galleries.xml
  def index
    @galleries = Gallery.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @galleries }
    end
  end

  # GET /galleries/1
  # GET /galleries/1.xml
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @gallery }
    end
  end

  # GET /galleries/new
  # GET /galleries/new.xml
  def new
    @gallery = Gallery.new
    @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @gallery }
    end
  end

  # GET /galleries/1/edit
  def edit
    @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
  end

  # POST /galleries
  # POST /galleries.xml
  def create
    @gallery = Gallery.new(params[:gallery])

    respond_to do |format|
      if @gallery.save
        flash[:notice] = 'Gallery was successfully created.'
        format.html { redirect_to(@gallery) }
        format.xml  { render :xml => @gallery, :status => :created, :location => @gallery }
      else
        @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
        format.html { render :action => "new" }
        format.xml  { render :xml => @gallery.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /galleries/1
  # PUT /galleries/1.xml
  def update
    respond_to do |format|
      if @gallery.update_attributes(params[:gallery])
        flash[:notice] = 'Gallery was successfully updated.'
        format.html { redirect_to(@gallery) }
        format.xml  { head :ok }
      else
        @user_groups_for_user = Lockdown::System.user_groups_assignable_for_user(current_user)
        format.html { render :action => "edit" }
        format.xml  { render :xml => @gallery.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /galleries/1
  # DELETE /galleries/1.xml
  def destroy
    @gallery.destroy

    respond_to do |format|
      format.html { redirect_to(galleries_url) }
      format.xml  { head :ok }
    end
  end

  private

  def find_model_instance
    @gallery = Gallery.find(params[:id])
  end

  def update_user_groups 
    #formatted for readability
		new_user_group_ids = params.collect do |p|
      if p[0] =~ /^grp_/
        p[0].split("_")[1].to_i 
      end
    end.compact

    @gallery.update_user_groups(new_user_group_ids)
  end
end
